package com.fzy.core.acegi;

import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;


/**
 * cache管理
 * 
 * @author cac
 */
public class AcegiCacheManager {
	protected final Logger log = Logger.getLogger(getClass());

	private ResourceCache resourceCache;

	private boolean resourceCacheInitialized = false;

	ResourceService resourceService;
	
	/**
	 * 修改Resource时更改resourceCache
	 */
	public void modifyResourceInCache(Resource resource,
			String orgResourceString) {
		Resource resourceDetails = resourceCache
				.getAuthorityFromCache(orgResourceString);
		if (resourceDetails != null)
			resourceCache.removeAuthorityFromCache(orgResourceString);
		resourceDetailsInCache(resource);

	}

	public void refreshCaches() {
		refreshResourceCache();
	}

	/**
	 * 初始化resourceCache
	 */
	public void initResourceCache() {
		if (!resourceCacheInitialized) {
			synchronized (this) {
				List resources = resourceService.getResources();
				for (Iterator iter = resources.iterator(); iter.hasNext();) {
					Resource resource = (Resource) iter.next();
					resourceDetailsInCache(resource);
				}
				resourceCacheInitialized = true;
			}
		}
	}

	public void refreshResourceCache() {
		resourceCacheInitialized = false;
		try {
			resourceCache.getCache().removeAll();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		initResourceCache();
	}

	/**
	 * 获取所有资源
	 */
	public List getResStrings() {
		return resourceCache.getResources();
	}

	/**
	 * 根据资源串获取资源
	 */
	public Resource getAuthorityFromCache(String resString) {
		return resourceCache.getAuthorityFromCache(resString);
	}
	
	/**
	 * 获取resource相应的权限并置于resourcecache中
	 */
	public void resourceDetailsInCache(Resource resource) {	
		resourceCache.putAuthorityInCache(resource);
	}

	public void setResourceCache(ResourceCache resourceCache) {
		this.resourceCache = resourceCache;
	}

	public ResourceCache getResourceCache() {
		return resourceCache;
	}

	public ResourceService getResourceService() {
		return resourceService;
	}

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

}
